package com.twetec.cms.adapter.pc.backend.tag;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.twetec.cms.adapter.pc.backend.tag.annotation.TplTag;
import com.twetec.cms.adapter.pc.backend.tag.doc.TagDocObject;
import com.twetec.cms.common.constant.ArticleEnum;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.website.*;
import com.twetec.cms.service.website.*;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.tag.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service()
@Scope("prototype")
@TplTag("article")
public class ArticleTag extends GeneralVarTagBinding {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private ArticleExtendService articleExtendService;

    @Autowired
    HttpServletRequest request;

    @Override
    public void render() {
        System.out.println("ArticleTag");

        // 接收标签参数
        Map result = Maps.newHashMap();
        // 文章id
        Long articleId = (this.getAttributeValue("articleId") instanceof String) ?
                Long.parseLong((String) this.getAttributeValue("articleId")) : (Long) this.getAttributeValue("articleId");

        // 查询文章信息 (基础信息, 扩展信息, 附件列表, 相关文章)
        // 基础信息(title,releaseTime,author,cover,coverList,coverType,type,gmtAnnouncementEnd,gmtAnnouncementStart,origin,summary)
        QueryWrapper<ArticlePO> articlePOQueryWrapper = new QueryWrapper<>();
        articlePOQueryWrapper.eq("ID", articleId);
        articlePOQueryWrapper.eq("IS_RECOVERY", 0);
        ArticlePO articlePO = articleService.getOne(articlePOQueryWrapper);

        if (!ValidateUtil.isNullOrEmpty(articlePO)) {
            // 文章标题
            String title = articlePO.getTitle();
            // 发布时间 Date
            String releaseTime = DateUtil.formatDateTime(articlePO.getReleaseTime());
            // 作者
            String author = articlePO.getAuthor();
            // 公告开始时间
            String gmtAnnouncementStart = DateUtil.formatDateTime(articlePO.getGmtAnnouncementStart());
            // 公告结束时间
            String gmtAnnouncementEnd = DateUtil.formatDateTime(articlePO.getGmtAnnouncementEnd());
            // 封面类型
            String coverType = articlePO.getCoverType();
            // 封面
//            String cover = articlePO.getCover();
//            ArrayList<String> coverUrlList = new ArrayList<>();
//            List<UrlConvert> convertList = JSON.parseArray(articlePO.getCover(), UrlConvert.class);
//            for (UrlConvert urlConvert : convertList) {
//                coverUrlList.add(urlConvert.getFileUrl());
//            }


            // 来源
            String origin = articlePO.getOrigin();
            // 文章类型
            String type = articlePO.getType();
            // 文章摘要
            String summary = articlePO.getSummary();
            // 封面
            List<Map<String, String>> coverMapList = new ArrayList<Map<String, String>>();
            // 将json字符数组转化为对象
            List<UrlConvert> urlConvertList = JSONArray.parseArray(articlePO.getCover(), UrlConvert.class);
            // 遍历，添加到map中
            for (UrlConvert urlConvert : urlConvertList) {
                HashMap<String, String> coverMap = new HashMap<>();
                coverMap.put("url", urlConvert.getFileUrl());
                coverMapList.add(coverMap);
            }

            // 扩展信息()
            QueryWrapper<ArticleExtendPO> articleExtendPOQueryWrapper = new QueryWrapper<>();
            articleExtendPOQueryWrapper.eq("ARTICLE_ID", articlePO.getId());
            ArticleExtendPO articleExtendPO = articleExtendService.getOne(articleExtendPOQueryWrapper);
            // 将扩展字段转换为集合再存放到map中
            HashMap<String, String> extendHashMap = new HashMap<>();
            if (!ValidateUtil.isNullOrEmpty(articleExtendPO)) {
                List<ExtendField> fieldList = JSON.parseArray(articleExtendPO.getExtendFieldList(), ExtendField.class);
                if (null != fieldList && !ValidateUtil.isNullOrEmpty(fieldList)) {
                    for (ExtendField extendField : fieldList) {
                        extendHashMap.put(extendField.getFieldCode(), extendField.getDefaultValue());
                        System.out.println(extendField);
                    }
                    result.put("extend", extendHashMap);
                }
                // content
                if (StringUtils.isNotEmpty(articleExtendPO.getContent())) {
                    result.put("content", articleExtendPO.getContent());
                }
            }

            // 如果文章类型是图文和公告
            String url = "";
            // 通过文章表里的siteId获取站点信息
            QueryWrapper<SitePO> sitePOQueryWrapper = new QueryWrapper<>();
            sitePOQueryWrapper.eq("ID", articlePO.getSiteId());
            SitePO sitePO = siteService.getOne(sitePOQueryWrapper);
            // 拼上站点的域名

            if (ArticleEnum.TYPE_GONG_GAO_ZI_XUN.getValue().equals(articlePO.getType()) ||
                    ArticleEnum.TYPE_TU_WEN_ZI_XUN.getValue().equals(articlePO.getType())) {
                ColumnPO columnPO = columnService.getById(articlePO.getColumnId());
                url = sitePO.getDomainUrl() + File.separator + columnPO.getEncodedXpath() + File.separator + articleId + ".html";

                result.put("url", url);
            } else {
                // 如果文章类型是下载文件和跳转链接,就从扩展表的content字段
                // 从扩展表中拿到content字段的内容
                if (!ValidateUtil.isNullOrEmpty(articleExtendPO) && StringUtils.isNotEmpty(articleExtendPO.getContent())) {

                        result.put("url", articleExtendPO.getContent());
                }
            }


            // 返回参数列表
			result.put("articleId", articleId);
			result.put("title", title);
			result.put("releaseTime", releaseTime);
			result.put("author", author);
			result.put("gmtAnnouncementStart", gmtAnnouncementStart);
			result.put("gmtAnnouncementEnd", gmtAnnouncementEnd);
			result.put("coverType", coverType);
			result.put("coverList", coverMapList);
			if (!ValidateUtil.isNullOrEmpty(coverMapList)) {
                result.put("cover", coverMapList.get(0).get("url"));
            }
			result.put("origin", origin);
			result.put("type", type);
			result.put("summary", summary);
			result.put("url", url.replace("/", "\\"));

			this.binds(result);
			this.doBodyRender();

        }

    }


    /**
     * 标签文档
     *
     * @return
     */
    public static TagDocObject doc() {
        TagDocObject tagDocObject = new TagDocObject();
        tagDocObject.setTagName("article");
        tagDocObject.setDesc("文章标签");
        tagDocObject.setExample("<#article articleId=\"1447752301597237250\" var=\"data\">\n" +
                "      <div><h1>${data.title!}</h1></div>\n" +
                "      <div>${data.releaseTime!}</div>\n" +
                "      <div>${data.author!}</div>\n" +
                "      <div>${data.summary!}</div>\n" +
                "\n" +
                "      <div> <b>${data.seoTitle!}</b> </div>\n" +
                "      <div> <b>${data.seoKeywords!}</b> </div>\n" +
                "      <div> <b>${data.seoDesc!}</b> </div>\n" +
                "\n" +
                "      <div>${data.content!}</div>\n" +
                "\n" +
                "      <div>${data.gmtAnnouncementStart!}</div>\n" +
                "      <div>${data.gmtAnnouncementEnd!}</div>\n" +
                "      <div><img src=\"${data.cover!}\" alt=\"图片\"></div>\n" +
                "\n" +
                "      </#article>");

        tagDocObject.setParamDesc("articleId：文章id\n" +
                "--------- var: 标签的数据结果集 ---------\n" +
                "title：文章标题\n" +
                "releaseTime：发布时间\n" +
                "author：作者\n" +
                "gmtAnnouncementStart：公告开始时间\n" +
                "gmtAnnouncementEnd：公告结束时间\n" +
                "coverType：封面图类型(单图DAN_TU,多图DUO_TU,横图HENG_TU)\n" +
                "coverList：封面图集合\n" +
                "cover：封面图\n" +
                "origin：来源\n" +
                "type：文章类型\n" +
                "summary：文章摘要\n" +
                "content：内容\n" +
                "attachmentList：附件信息\n" +
                "relevantList：相关文章信息\n" +
                "url：跳转链接");

        tagDocObject.setOtherDesc("无");

        return tagDocObject;
    }

}
